#include "MLTools_TxtFileLoader.h"
#include "MLTools.h"
_MYLABLIB_BEGIN

CMLTools_TxtFileLoader::CMLTools_TxtFileLoader(void)
{
	m_nStartPos = -1;
	m_nEndPos = -1;
}

CMLTools_TxtFileLoader::~CMLTools_TxtFileLoader(void)
{
	if (m_FileStream.is_open())
		m_FileStream.close();
}

int CMLTools_TxtFileLoader::Initialize(const std::wstring& wstrFileName, int nStartPos /*=-1*/, int nEndPos/*=-1*/)
{
	m_nStartPos = nStartPos;
	m_nEndPos = nEndPos;
	m_FileStream.open(wstrFileName.c_str());
	if (m_FileStream.fail())
	{
		ML_ASSERT(false);
		return -1;
	}
	m_nPos = 0;
	if (m_nStartPos > 0)
	{
		std::wstring wstrLine;
		while(m_FileStream.eof() == false)
		{
			if (m_nPos == m_nStartPos)
				break;
			std::getline(m_FileStream, wstrLine);
			m_nPos++;
		}
	}

	return 0;
}

int CMLTools_TxtFileLoader::Load(CMLDataSet& dataSet)
{
	std::wstring wstrLine;
	CMLDataPoint dataPoint;
	while(m_FileStream.eof() == false)
	{
		if (m_nPos == m_nEndPos)
			break;

		std::getline(m_FileStream, wstrLine);
		if (wstrLine.length() == 0)
			break;

		dataPoint.FromWString(wstrLine);
		dataSet.Insert(dataPoint);
		m_nPos++;
	}
	return 0;
}

int CMLTools_TxtFileLoader::Load(CMLDataSet& dataSet, int nBufSize)
{
	int nSize = 0;
	std::wstring wstrLine;
	CMLDataPoint dataPoint;

	if (dataSet.Count() < nBufSize)
		dataSet.Resize(nBufSize);

	while(m_FileStream.eof() == false && nSize < nBufSize)
	{
		if (m_nPos == m_nEndPos)
			break;

		std::getline(m_FileStream, wstrLine);
		if (wstrLine.length() == 0)
			break;

		dataPoint.FromWString(wstrLine);
		dataSet.Set(nSize, dataPoint);
		nSize++;
		m_nPos++;
	}

	if (dataSet.Count() > nSize)
	{
		dataSet.Delete(nSize, dataSet.Count() - nSize);
	}
	return 0;
}

void CMLTools_TxtFileLoader::Close()
{
	m_FileStream.close();
	m_FileStream.clear();
}

_MYLABLIB_END
